
package com.android.formula.utils;

import java.text.DecimalFormat;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.text.TextUtils;
import android.widget.ImageView;

import com.android.formula.R;

/**
 * The class provides methods is used in others class.
 */
public class CommonUtils {
    // private static final String TAG = "CommonUtils";

    @SuppressWarnings("unchecked")
    /**
     * execute an asyntask. From android 3.0, we have to start asyntask by
     * calling executeOnExcecutor. If we call execute, list of asyntasks will be
     * run sequentially
     */
    @SuppressLint("NewApi")
    public static <T> void executeAsyTask(AsyncTask<T, ?, ?> task, T... params) {
        if (Build.VERSION.SDK_INT >= 11) {
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
        } else {
            task.execute(params);
        }
    }

    /**
     * Get file name (%s).
     * 
     * @param fileName
     * @return The file name string:ex:(banner.json)
     */
    public static String getFileName(Context context, String fileName) {
        if (context == null || TextUtils.isEmpty(fileName)) {
            return "";
        }
        String name = "";
        if (!TextUtils.isEmpty(fileName)) {
            name = context.getString(R.string.file_name_string, fileName);
            name = Constants.SPACE_CHARACTER + name;
        }
        return name;
    }

    /**
     * format number has "," in the three-digit
     * 
     * @param number
     * @return formattedString
     */
    public static String formatNumber(String number) {
        DecimalFormat formatter = new DecimalFormat("#,###,###");
        try {
            String formattedString = formatter.format(Long.parseLong(number));
            return formattedString;
        } catch (Exception e) {
            return number;
        }
    }

    public static void setImageFromDrawable(Context context, String imageId, ImageView imgView) {
        if (imgView != null) {
            int imageResource = context.getResources().getIdentifier("@drawable/" + imageId, null,
                    context.getPackageName());
            if (imageResource > 0) {
                Drawable resTrick = context.getResources().getDrawable(imageResource);
                imgView.setImageDrawable(resTrick);
            } else {
                imgView.setImageResource(R.drawable.no_image);
            }
        }
    }

    public static Bitmap decodeBitmap(Context context, String fileUrl) {
        Bitmap bitmap = null;
        bitmap = BitmapFactory.decodeFile(fileUrl);
        if (bitmap == null) {
            bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.no_image);
        }
        return bitmap;
    }
}
